package org.mx.service.rest.graphql;

import org.mx.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * 描述： 根据GraphQL Schema创建GraphQL的工程类
 *
 * @author john peng Date time 2018/11/25 11:12 AM
 */
public class GraphQLFactory {
	private static final Logger logger = LoggerFactory.getLogger(GraphQLFactory.class);

	private GraphQLUtils graphQLUtils = null;

	private ApplicationContext context;

	/**
	 * 构造函数
	 * 
	 * @param context Spring IoC上下文
	 */
	public GraphQLFactory(ApplicationContext context) {
		super();
		this.context = context;
	}

	/**
	 * 根据指定的GraphQL Schema Key获取GraphQL工具
	 *
	 * @return GraphQL工具
	 */
	public GraphQLUtils getUtils() {
		return graphQLUtils;
	}

	/**
	 * 根据配置初始化GraphQL工厂
	 */
	public void init() {
		GraphQLConfigBean config = context.getBean(GraphQLConfigBean.class);
		if (StringUtils.isBlank(config.getSchema())) {
			if (logger.isWarnEnabled()) {
				logger.warn("There are not any GraphQL Schema be defined.");
			}
			return;
		}
		if (StringUtils.isBlank(config.getPathType())) {
			config.setPathType("CLASSPATH");
		}
		graphQLUtils = new GraphQLUtils();
		if ("classpath".equalsIgnoreCase(config.getPathType()) || "class_path".equalsIgnoreCase(config.getPathType())) {
			graphQLUtils.initByClasspath(config.getSchema(), context);
		} else {
			graphQLUtils.initByFile(config.getSchema(), context);
		}
	}

	/**
	 * 销毁GraphQL工厂
	 */
	public void destroy() {
		graphQLUtils = null;
	}
}
